package SqlGenerator;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;

public class SqlFactory {
    ArrayList<TableInfo> tablelist = new ArrayList<>();

    public String processadd(String tablename, Field field){
        StringBuilder sql = new StringBuilder();
        for(TableInfo tableInfo:tablelist){
            if(tableInfo.getTableName().equals(tablename))
            {
                if(!tableInfo.samename(field)){
                ColumnInfo columnInfo = tableInfo.addcolumn(field);
                if (columnInfo != null) {
                    sql.append("ALTER TABLE "+tablename+"\nADD "+columnInfo.toString());
                }
                break;
                }
                else {
                    ColumnInfo columnInfo = tableInfo.addcolumn(field);
                    if (columnInfo != null) {
                        sql.append("ALTER TABLE "+tablename+"\nALTER COLUMN  "+columnInfo.toString());
                    }
                    break;
                }
            }
        }
        return sql.toString();
    }
    public String processalter(String tablename,String columnname){
        StringBuilder sql = new StringBuilder();
        for(TableInfo tableInfo:tablelist){
            if(tableInfo.getTableName().equals(tablename)&&tableInfo.removecolumn(columnname))
            {
                sql.append("ALTER TABLE "+tablename+"\nDROP COLUMN "+columnname);
                break;
            }
        }
        return sql.toString();
    }
    public String processrename(String tablename,String newname){
        StringBuilder sql = new StringBuilder();
        for(TableInfo tableInfo:tablelist){
            if(tableInfo.getTableName().equals(tablename)){
                sql.append("RENAME TABLE "+tablename+" to "+newname);
                tableInfo.setTableName(newname);
                break;
            }
        }
        return sql.toString();
    }
    public String processremove(String tablename){
        StringBuilder sql = new StringBuilder();
        for(TableInfo tableInfo:tablelist){
            if(tableInfo.getTableName().equals(tablename)){
                sql.append("DROP TABLE "+tablename);
                tablelist.remove(tableInfo);
                break;
            }
        }
        return sql.toString();
    }
    public String TableCreate(Class<?>[] claz){//class文件所在根目录
        StringBuilder sql = new StringBuilder();

        for(Class classFiles:claz){
                TableInfo table = new TableInfo().parse(classFiles);
                if(table!=null){
                    sql.append(table.toString());
                    //tablelist.add(table);
                }
        }
        return sql.toString();
    }
}
